import axios from 'axios';
import { ElMessage } from 'element-plus'
import { dayjs } from 'element-plus';

export const MethodType = {
    GET: 'GET',
    POST: 'POST',
    PUT: 'PUT',
    DELETE: 'DELETE',
    PATCH: 'PATCH'
};

const instance = axios.create({
    baseURL: '/',
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json;charset=UTF-8'
    }
})

export const request = (config: any) => {
    const {
        url,
        method = MethodType.GET,
        params = {
            ...config.params,
            // StartDate: dayjs().subtract(3, 'years').format('YYYY-MM-DD'),
            // EndDate: dayjs().format('YYYY-MM-DD')
        },
        headers = {},
    } = config;
    return new Promise((resolve, reject) => {
        instance({
            url: `/api${url}`,
            method,
            params,
            headers,
        }).then(
            (res: any) => {
                if (res.data.code === 400) {
                    // userStore.handleLoginOut();
                }
                resolve(res);
            }
        )
            .catch((error: any) => {
                console.log(error);
                ElMessage({
                    showClose: true,
                    message: typeof error.response.data === 'string' ? error.response.data : JSON.stringify(error.response.data),
                    type: 'error',
                });
                reject(error);
                if (error.response.status === 403) {
                    // 返回403无权限则重新发起登录流程
                    // userStore.handleLoginOut();
                }
                if (error.response.status === 401) {
                    // 返回403无权限则重新发起登录流程
                }
            });
    });
};